package com.xbongbong.pro.rabbitmq.producer.impl;

import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.pro.enums.errorcodes.MessageErrorCodeEnum;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.rabbitmq.binders.AIProducerBinder;
import com.xbongbong.pro.rabbitmq.producer.AIProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @Description: AI消息发送生产者接口实现类
 * @Author: jiping.yang
 * @Date: 2022-09-15  11:08
 * @version: v1.0
 **/
@Service("aiProducer")
@EnableBinding(AIProducerBinder.class)
public class AIProducerImpl implements AIProducer {

    private static final Logger LOG = LoggerFactory.getLogger(AIProducerImpl.class);

    private static final String HEADER_NAME = "type";
    @Resource
    private AIProducerBinder aiProducerBinder;

    /**
     * AI消息发送
     * @param message 入参
     * @throws XbbException
     * @date: 2022-9-15 10:45
     */
    @Override
    public void sendMessage(MessageRabbitMqDTO message, PushTypeEnum pushTypeEnum) throws XbbException{
        if (CollectionsUtil.isEmpty(message.getUserIds())) {
            //目前发现太多推送人为空的消息进入mq，前置拦截
            return;
        }
        MessageBuilder messageBuilder;
        MessageHeaderAccessor messageHeaderAccessor = new MessageHeaderAccessor();
        Object header;
        if (Objects.nonNull(pushTypeEnum) && Objects.nonNull(message)) {
            switch (pushTypeEnum) {
                case DATA_IMPORT:
                    header = PushTypeEnum.DATA_IMPORT;
                    messageHeaderAccessor.setHeader(HEADER_NAME, header);
                    messageBuilder = MessageBuilder.withPayload(message).setHeaders(messageHeaderAccessor);
                    aiProducerBinder.aiOutput().send(messageBuilder.build());
                    break;
                case TRAIN_MODEL:
                    header = PushTypeEnum.TRAIN_MODEL;
                    messageHeaderAccessor.setHeader(HEADER_NAME, header);
                    messageBuilder = MessageBuilder.withPayload(message).setHeaders(messageHeaderAccessor);
                    aiProducerBinder.aiOutput().send(messageBuilder.build());
                    break;
                case UNKNOWN:
                    throw new XbbException(MessageErrorCodeEnum.API_ERROR_380001);
                default:
                    break;
            }
        }
    }
}
